package useraddress

import (
	"context"

	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetUserAddressByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetUserAddressByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetUserAddressByIdLogic {
	return &BackendGetUserAddressByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetUserAddressByIdLogic) BackendGetUserAddressById(in *user.IDReq) (*user.UserAddressInfo, error) {
	if in.Id == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	res, err := l.svcCtx.UserAddress.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, err
	}

	var isDefault uint32
	if res.IsDefault > 0 {
		isDefault = 1
	}
	var geographic []*user.UserMetaInfo
	if res.Geographic.Valid {
		if err = res.Geographic.Unmarshal(&geographic); err != nil {
			// logx.Infof("BackendGetUserAddressById: err %+v ", err)
			logx.Errorw("BackendGetUserAddressById Geographic.Unmarshal err", logx.Field("detail", err.Error()))
		}
	}

	return &user.UserAddressInfo{
		Id:              pointy.GetPointer(res.UserAddressID),
		UserId:          pointy.GetPointer(res.UserID),
		Label:           pointy.GetPointer(res.Label),
		Consignee:       pointy.GetPointer(res.Consignee),
		Mobile:          pointy.GetPointer(res.Mobile),
		Province:        pointy.GetPointer(res.PostalCode),
		City:            pointy.GetPointer(res.City),
		District:        pointy.GetPointer(res.District),
		Street:          pointy.GetPointer(res.Street),
		DetailedAddress: pointy.GetPointer(res.DetailedAddress),
		PostalCode:      pointy.GetPointer(res.PostalCode),
		RegionCode:      pointy.GetPointer(res.RegionCode),
		IsDefault:       pointy.GetPointer(isDefault),
		Status:          pointy.GetPointer(uint32(res.Status)),
		LastUsedAt:      pointy.GetPointer(modelx.FormatNullDotTime(res.LastUsedAt, "")),
		CreatedAt:       pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:       pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:       pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Geographic:      geographic,
	}, nil
}
